package com.neuedu.bases;

import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtil {

    private static String url = "jdbc:mysql://localhost:3306/myMaintain";//固定格式
    private static String name = "root";//数据库用户名
    private static String password = "112233";//数据库密码

    /**
     * 该方法用于获取连接对象
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,name,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 该方法用于释放资源
     */
    public static void release(Connection conn,Statement st,ResultSet rs) {
        closeRs(rs);
        closeSt(st);
        closeConn(conn);
    }
    public static void release(Connection conn,Statement st) {
        closeSt(st);
        closeConn(conn);
    }

    private static void closeRs(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            rs = null;
        }
    }
    private static void closeSt(Statement st) {
        try {
            if (st != null) {
                st.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            st = null;
        }
    }
    private static void closeConn(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn = null;
        }
    }

    public static String testQuery(String id) {   //查询操作
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.获取连接对象（这里使用到的JDBCUtil类就是我们上面写的工具类）
            connection = JDBCUtil.getConnection();
            //2.根据连接对象，得到statement
            statement = connection.createStatement();
            //3.执行sql语句，返回ResultSet
            String sql = "select * from issues_employee";
            resultSet = statement.executeQuery(sql);
            //4.遍历结果
            while(resultSet.next()) {
                String issue_id = resultSet.getString("issue_id");
                if(issue_id.equals(id)){
                    return resultSet.getString("state");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
